package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @文件名: LoginCheckFilter
 * @作者: DX
 * @创建日期: 2025/10/11
 * @描述:
 */
@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    private static final String IGNORE_URLS = "/login";
    private static final String TOKEN_HEADER = "token";

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;


        String path = request.getServletPath();
        log.info("拦截路径{}",path);

        if (ObjectUtil.equals(IGNORE_URLS, path )){
            chain.doFilter(request, response);
            return;
        }

        String token = request.getHeader(TOKEN_HEADER);
        if (ObjectUtil.isEmpty(token)){
            response.setStatus(401);
            return;
        }

        try {
            Claims claims = JwtUtils.parseToken(token);

            Object id = claims.get("id");
            log.info("id: {}", id);
            String username = claims.get("username", String.class);
            log.info("username: {}", username);

            chain.doFilter(request, response);
            return;
        }catch (Exception e) {
            log.error("token解析失败", e);
            response.setStatus(401);
        }
    }
}
